package com.apes.auto.autoparts.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.auto.autoparts.model.BehaviorRecord;
import com.apes.auto.autoparts.repository.BehaviorRecordRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by lishikun on 2021/4/26 18:02
 */
@Service("behaviorRecordService")
public class BehaviorRecordService extends DomainService {

    @Autowired
    BehaviorRecordRepository behaviorRecordRepository;

    @Autowired
    EnumerationRepository enumerationRepository;

    public BehaviorRecord save(SimpleRequest request) {
        JSONObject jo = request.getJO();
        BehaviorRecord behaviorRecord = request.getO(BehaviorRecord.class);
        User user = (User) request.getCurrentUser();
        Dept dept = SpringManager.getBean(PostRepository.class).findOne(request.getPostId()).getDept();
        Enumeration operatingType = enumerationRepository.findOne(request.getJO().getJSONObject("operatingType").getString("id"));
        behaviorRecord.setOperatingType(operatingType);
        behaviorRecord.setUserId(user != null? user.getOrigin() : "");
        behaviorRecord.setUserName(user != null ? user.getName(): "");
        behaviorRecord.setDeptId(dept != null ? dept.getId() : "");
        behaviorRecord.setDeptName(dept != null ? dept.getName() : "");
        behaviorRecord.setOperatingData(new Date());
        return behaviorRecordRepository.saveAndFlush(behaviorRecord);
    }
}
